package cn.turboinfo.fuyang.api.domain.admin.usecase.spec;

import cn.turboinfo.fuyang.api.domain.common.service.spec.SpecService;
import cn.turboinfo.fuyang.api.domain.common.service.spec.SpecSetRelService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.spec.Spec;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.base.enums.YesNoStatus;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Component
public class SpecDeleteUseCase extends AbstractUseCase<SpecDeleteUseCase.InputData, SpecDeleteUseCase.OutputData> {
    private final SpecService specService;

    private final SpecSetRelService specSetRelService;

    @Override
    protected OutputData doAction(InputData inputData) {

        Long id = inputData.getId();

        Spec spec = specService.getByIdEnsure(id);

        if (spec.getAllowDelete().equals(YesNoStatus.NO)) {
            throw new RuntimeException(String.format("%s 不允许删除", spec.getName()));
        }

        boolean allowDelete = spec.getAllowDelete().equals(YesNoStatus.YES);

        // 删除子规格
        List<Spec> childList = specService.findByParentId(id);
        for (Spec it : childList) {
            if (it.getAllowDelete().equals(YesNoStatus.YES)) {
                specService.deleteById(it.getId());
            } else {
                allowDelete = false;
            }
        }

        // 删除规格
        if (allowDelete) {
            specService.deleteById(id);
        } else {
            throw new RuntimeException(String.format("《%s》规格不允许删除", spec.getName()));
        }

        return OutputData.builder()
                .build();
    }

    @EqualsAndHashCode(
            callSuper = true
    )
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {
        @NotNull(
                message = "编码不能为空"
        )
        private Long id;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
    }
}
